# -*- coding: utf-8 -*-
# author:jiangsibei

import os,inspect
from tools import Config
from airtest.core.api import *
from airtest.core.android.adb import ADB
from tools.log import logger
from poco.drivers.cocosjs import CocosJsPoco
from  page_elements.Common import *



# 获取工程路径
pro_path = os.path.dirname(inspect.getfile(inspect.currentframe())) + os.path.sep + ".."
# 获取case的图片路径
img_path = os.path.join(pro_path, 'page_elements')
# 获取对应图片路径
case_img_Common = os.path.join(img_path,'Common_Pic')

adb = ADB().adb_path

class AdbOperation:

    def __init__(self, mdevice=""):
        # 获取当前文件的上层路径
        self._parentPath = os.path.abspath(os.path.dirname(inspect.getfile(inspect.currentframe())) + os.path.sep + ".")
        # 获取当前项目的根路径
        self._rootPath = os.path.abspath(os.path.dirname(self._parentPath) + os.path.sep + ".")
        self._configPath = self._rootPath + "/config.ini"
        # 获取项目名称
        self._pro_name = Config.getProName(self._configPath, "pro_name")

        # 获取项目配置
        self._devicesList = Config.getProConfig(self._configPath, "deviceslist", self._pro_name)
        self._packagePath = Config.getProConfig(self._configPath, "apkpath", self._pro_name)[0]
        self._packageName = Config.getProConfig(self._configPath, "packname", self._pro_name)[0]
        self._timeout_of_per_action = int(Config.getProConfig(self._configPath, "timeout_of_per_action","basic")[0])
        self._mdevice = mdevice

    # 获取设备列表
    def get_devicesList(self):
        return self._devicesList
    # 获取包名
    def get_packagename(self):
        return self._packageName

    # 获取当前设备id
    def get_mdevice(self):
        return self._mdevice

    # 获取每步操作的延时时间
    def get_timeout_of_per_action(self):
        return self._timeout_of_per_action

    def connect_device(self,device):
        # 调用airtest的各个方法连接设备
        # connect_device("Android:///" + devices)
        logger.info("连接app,devicename={}".format(device))
        try:
            connect_device("android://127.0.0.1:5037/{}?cap_method=javacap&touch_method=adb".format(device))
        except Exception as e:
            logger.error(e)


    # 本方法用于读取实时的设备连接
    def getdevices(self):
        deviceslist = []
        for devices in os.popen(adb + " devices"):
            if "\t" in devices:
                if devices.find("emulator") < 0:
                    if devices.split("\t")[1] == "device\n":
                        devices = devices.split("\t")[0]
                        deviceslist.append(devices)
                        logger.info("设备{}被添加到deviceslist中".format(devices))
        return deviceslist

    # 启动APP的方法，核心是airtest的start_app函数 TODO 先简单启动，后续会清空缓存、权限、弹窗的处理
    def StartApp(self):
        device = G.DEVICE.uuid
        dev = connect_device("Android:///" + device)
        #使用adb命令开启麦克风权限
        dev.shell('pm grant  com.zuoyebang.bangbangshizi android.permission.RECORD_AUDIO')
        #开启相机权限
        dev.shell('pm grant  com.zuoyebang.bangbangshizi android.permission.CAMERA')
        #开启存储权限
        dev.shell('pm grant  com.zuoyebang.bangbangshizi android.permission.WRITE_EXTERNAL_STORAGE')


        logger.info("{}进入StartAPP函数".format(device))
        start_app(self.get_packagename())
        sleep(5)
        if exists(Template(r"{}/Privacy_authorization.png".format(case_img_Common))):
            touch(Template(r"{}/Authorization_agree.png".format(case_img_Common)))

        sleep(20) #启动后延时10s
        base_poco = CocosJsPoco()
        # 判断是否有开屏弹窗---根据弹窗上面的关闭按钮判断
        Close_Button_name = Common.Close_Button['name']
        Close_Button_Ele = base_poco(Close_Button_name)
        if Close_Button_Ele.exists():
            Close_Button_Ele.click()
        sleep(1)

        #判断是否有今日任务弹窗
        Today_Studay_Windows_name = Common.Today_Studay_Windows['name']
        Today_Studay_Windows_Ele = base_poco(Today_Studay_Windows_name)
        if Today_Studay_Windows_Ele.exists():
            Today_Studay_Windows_Close_name = Common.Today_Studay_Windows_Close['name']
            Today_Studay_Windows_Close_Ele = base_poco(Today_Studay_Windows_Close_name)
            Today_Studay_Windows_Close_Ele.click()
        sleep(1)

    def InstallApp(self):
        android = device()
        try:
            if android.check_app(self.get_packagename()):
                self.Uninstall(android)
        except Exception as e:
            install(r"/Users/jiangsibei/Desktop/code/shizi_uiautomation/bangbangshizi.apk")

    #清除应用数据
    def ClearApp(self):

        clear_app(self.get_packagename())

    #停止app
    def StopApp(self):
        sleep(3) #延时3s再停止
        stop_app(self.get_packagename())

    #卸载app
    def Uninstall(self,android):
        android.uninstall(self.get_packagename())



